package cn.itsource.user.controller;

import cn.itsource.basic.constant.WechatConstant;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.user.domain.dto.LogininfoDto;
import cn.itsource.user.service.IWechatService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private IWechatService wechatService;

    /**
     * 拉起二维码
     * @return
     */
    @RequestMapping("/tologin")
    public String tologin(){
        String codeUrl = WechatConstant.CODE_URL.replace("APPID", WechatConstant.APPID).replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        return "redirect:"+codeUrl;
    }

    /**
     * 二维码扫描成功后，跳转到回调接口，并且携带授权码
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code){
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }

    /**
     * 处理回调接口
     * @return
     */
    @PostMapping("/handleCallback")
    @ResponseBody
    public AjaxResult handleCallback(@RequestBody Map<String,String> param){
        try {
            Map<String,Object> map = wechatService.handleCallback(param.get("code"));
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
     * 微信绑定手机号
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody LogininfoDto logininfoDto){
        try {
            System.out.println(logininfoDto);
            Map<String,Object> map = wechatService.binderPhone(logininfoDto);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }
}
